package org.example;

import com.zaxxer.hikari.HikariDataSource;
import org.example.springbatchdemo.config.DataSourceProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author wangxiaolin
 */
@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceConfig {

    private final DataSourceProperties properties;

    public DataSourceConfig(DataSourceProperties properties) {
        this.properties = properties;
    }

    @Bean(name = "sourceDataSource")
    @Primary
    public DataSource sourceDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(properties.getSource().getUrl()); 
        dataSource.setUsername(properties.getSource().getUsername());
        dataSource.setPassword(properties.getSource().getPassword());
        dataSource.setDriverClassName(properties.getSource().getDriverClassName());

        dataSource.setMaximumPoolSize(20);
        dataSource.setMinimumIdle(5);
        return dataSource;
    }

    @Bean(name = "targetDataSource")
    public DataSource targetDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(properties.getTarget().getUrl());
        dataSource.setUsername(properties.getTarget().getUsername());
        dataSource.setPassword(properties.getTarget().getPassword());
        dataSource.setDriverClassName(properties.getTarget().getDriverClassName());
        dataSource.setMaximumPoolSize(20);
        dataSource.setMinimumIdle(5);
        return dataSource;
    }

    @Bean(name = "sourceTransactionManager")
    @Primary
    public DataSourceTransactionManager sourceTransactionManager(@Qualifier("sourceDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "targetTransactionManager")
    public DataSourceTransactionManager targetTransactionManager(@Qualifier("targetDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}